import { createRouter, createWebHistory } from 'vue-router'
import { isLoggedIn } from '../utils/cookieUtils.js'

// 懒加载路由组件
const Home = () => import('../views/Home.vue')
const About = () => import('../views/About.vue')
const Dashboard = () => import('../views/Dashboard.vue')
const Login = () => import('../views/Login.vue')
// 新增管理系统功能页面
const UserManagement = () => import('../views/UserManagement.vue')
const ProductManagement = () => import('../views/ProductManagement.vue')
const Settings = () => import('../views/Settings.vue')
const NotFound = () => import('../views/NotFound.vue')

// 路由配置
const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: {
      requiresAuth: true,
      title: '首页',
      icon: 'home'
    }
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: Dashboard,
    meta: {
      requiresAuth: true,
      title: '仪表盘',
      icon: 'data-line'
    }
  },
  {
    path: '/users',
    name: 'UserManagement',
    component: UserManagement,
    meta: {
      requiresAuth: true,
      title: '用户管理',
      icon: 'user'
    }
  },
  {
    path: '/products',
    name: 'ProductManagement',
    component: ProductManagement,
    meta: {
      requiresAuth: true,
      title: '产品管理',
      icon: 'goods'
    }
  },
  {
    path: '/settings',
    name: 'Settings',
    component: Settings,
    meta: {
      requiresAuth: true,
      title: '系统设置',
      icon: 'setting'
    }
  },
  {
    path: '/about',
    name: 'About',
    component: About,
    meta: {
      title: '关于我们',
      icon: 'info'
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: {
      requiresAuth: false,
      title: '登录'
    }
  },
  // 404页面
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: NotFound,
    meta: {
      title: '页面不存在'
    }
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫 - 处理权限验证和页面标题设置
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 管理系统` : '管理系统'
  
  // 检查路由是否需要认证
  const requiresAuth = to.meta.requiresAuth !== false
  
  // 检查用户是否已登录（通过检查Cookie中的sso_token，并验证JWT是否过期）
  const isLoggedInSuccess = isLoggedIn()
  
  // 如果路由需要认证且用户未登录，则跳转到登录页
  if (requiresAuth && !isLoggedInSuccess) {
    // 如果to.fullPath为空或为根路径，则不添加redirect参数
    const query = to.fullPath && to.fullPath !== '/' ? { redirect: to.fullPath } : {}
    next({ path: '/login', query })
  } 
  // 如果用户已登录且访问登录页，则跳转到首页
  else if (to.path === '/login' && isLoggedInSuccess) {
    next({ path: '/' })
  } 
  // 其他情况正常跳转
  else {
    next()
  }
})

export default router